package com.suneast.suneaststore.modules.personal.info;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.suneast.suneaststore.API;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.main.BottomFragment;
import com.suneast.suneaststore.modules.personal.info.event.ChangeHeadImg;
import com.suneast.suneaststore.modules.personal.sign.event.ExitCurrentAccountEvent;
import com.suneast.suneaststore.ui.fragments.BaseFragment;
import com.suneast.suneaststore.modules.common.CommonUtil;
import com.suneast.suneaststore.util.log.LatteLogger;
import com.suneast.suneaststore.util.net.RestClient;
import com.suneast.suneaststore.util.net.upload.ResultEvent;
import com.suneast.suneaststore.util.net.upload.UploadHandler;
import com.tencent.bugly.beta.Beta;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.noobie.photopicker.entity.Photo;
import org.noobie.photopicker.ui.PhotoPickerFragment;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class HeadImgFragment extends BaseFragment {

    public static final int HeadImg = 0;

    @Override
    public int setLayout() {
        return R.layout.fragment_head_img;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        toolbar.setNavigationOnClickListener(v -> popTo(BottomFragment.class, false));
        if (headImgUrl != null) {
            Glide.with(_mActivity).load(headImgUrl).into(headImg);
        }
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private String headImgUrl;

    public HeadImgFragment withHeadImgUrl(String headImgUrl) {
        this.headImgUrl = headImgUrl;
        return this;
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.img_head)
    ImageView headImg;

    @OnClick({R.id.layout_modify_head_img, R.id.layout_modify_password,
            R.id.layout_feedback, R.id.layout_about_us, R.id.layout_check_version, R.id.btn_exit_account})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.layout_modify_head_img: {
                //选择图片 并上传
                HeadImgFragmentPermissionsDispatcher.startPhotoPickerWithPermissionCheck(this);
            }
            break;
            case R.id.layout_modify_password: {
                start(new ModifyPasswordFragment());
            }
            break;
            case R.id.layout_feedback: {
                //todo 打开意见反馈界面
            }
            break;
            case R.id.layout_about_us: {
                start(new SimpleAboutUsFragment());
            }
            break;
            case R.id.layout_check_version: {
                Beta.checkUpgrade();//检测版本
            }
            break;
            case R.id.btn_exit_account: {
                AccountManager.exitCurrentAccount();
                EventBus.getDefault().post(new ExitCurrentAccountEvent());
                pop();
            }
            break;
        }
    }

    void uploadHeadImg(String filePath) {
        LatteLogger.e("test", " uploadHeadImg token = " + AccountManager.getToken());
        RestClient
                .builder()
                .url(API.UPDATE_HEAD_IMG)
                .params("token", AccountManager.getToken())
                .file(filePath)
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject dataObj = CommonUtil.parseDataFromRootJSON(response);
                    if (dataObj != null) {
                        String url = dataObj.getString("url");
                        Context context = getContext();
                        if (context != null) {
                            Glide.with(getContext()).load(url).into(headImg);
                        }
                        EventBus.getDefault().post(new ChangeHeadImg(url));
                    }
                })
                .error((code, msg) -> {
                    LatteLogger.e("error", "uploadHeadImg error code = "
                            + code + " msg = " + msg);
                })
                .failure(() -> {
                    LatteLogger.e("error", "uploadHeadImg failure ");
                })
                .build()
                .upload();
    }

    void showRationaleForReadStorage(PermissionRequest request) {
        // NOTE: Show a rationale to explain why the permission is needed, e.g. with a dialog.
        // Call proceed() or cancel() on the provided PermissionRequest to continue or abort
        Context context = getContext();
        if (context != null) {
            new AlertDialog.Builder(getContext())
                    .setMessage(R.string.permission_read_storage_rationale)
                    .setPositiveButton(R.string.text_allow, (dialog, button) -> request.proceed())
                    .setNegativeButton(R.string.text_deny, (dialog, button) -> request.cancel())
                    .show();
        }
    }

    @NeedsPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
    void startPhotoPicker() {
        startForResult(new PhotoPickerFragment(), HeadImg);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        HeadImgFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == HeadImgFragment.HeadImg) {
            if (resultCode == Activity.RESULT_OK) {
                ArrayList<Photo> photoList = data.getParcelableArrayList("photos");
                if (photoList != null && photoList.size() > 0) {
                    headImgPath = photoList.get(0).getFilePath();
                    UploadHandler.upload(headImgPath);
                }
            }
        }
    }

    private String headImgPath = null;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadResult(ResultEvent event) {
        LatteLogger.d("test", "upload result = " + event.getValue());
        if (event.getValue() == Flag.Result.SUCCEED) {
            if(headImgPath != null){
                Glide.with(_mActivity).load(headImgPath).into(headImg);
                headImgPath = null;
            }
            String key = event.getKey();
            //todo 上传 key 给后台
//            uploadHeadImg();
        } else {
            Toast.makeText(_mActivity, "头像修改失败", Toast.LENGTH_SHORT).show();
        }
    }
}
